$(document).ready(function(){
   calculate();

});


function calculate(){

    var miTabla = document.getElementById("table_content");

    for (var i=2; i< (miTabla.rows.length - 1); i++) {

        var tr = miTabla.getElementsByTagName('tr')[i];
        var duration = tr.getElementsByTagName('th')[3].firstChild.value;
        var predecessor = tr.getElementsByTagName('th')[11].firstChild.value;

        //var PD = miTabla.getElementsByTagName('tr')[1].getElementsByTagName('th')[6].firstChild.value;
        var PD = miTabla.getElementsByTagName('tr')[1].getElementsByTagName('th')[6].children[1].value;

        if(  duration != "" && PD != '' ){
            var strPlanned = '';
            var strCorrected = '';

            if( predecessor == 1 )
                strPlanned = miTabla.getElementsByTagName('tr')[predecessor].getElementsByTagName('th')[6].children[1].value;
            else{
                strPlanned = miTabla.getElementsByTagName('tr')[predecessor].getElementsByTagName('th')[4].children[1].value;
                strCorrected = miTabla.getElementsByTagName('tr')[predecessor].getElementsByTagName('th')[6].children[1].value;
            }

            if( strPlanned != '' ){

                var splitPlanned = strPlanned.split("/");
                var strPlanned = splitPlanned[1]+ "/" + splitPlanned[0] + "/20" + splitPlanned[2];

                var datePlanned = new Date(strPlanned);

                $(tr.getElementsByTagName('th')[4].children[0]).datepicker( "option", "dateFormat", 'dd/mm/y' );
                tr.getElementsByTagName('th')[4].children[0].value = $.datepicker.formatDate('dd/mm/y', addDays(datePlanned,duration));
                $(tr.getElementsByTagName('th')[4].children[0]).datepicker( "option", "dateFormat", 'dd/M/y' );
            }  else
                tr.getElementsByTagName('th')[4].children[1].value = '';

            if( strCorrected != ''){
                var splitCorrected = strCorrected.split("/");
                var strCorrected = splitCorrected[1]+ "/" + splitCorrected[0] + "/20" + splitCorrected[2];

                var dateCorrected = new Date(strCorrected);

                $(tr.getElementsByTagName('th')[5].children[0]).datepicker( "option", "dateFormat", 'dd/mm/y' );
                tr.getElementsByTagName('th')[5].children[0].value = $.datepicker.formatDate('dd/mm/y', addDays(dateCorrected,duration)); ;
                $(tr.getElementsByTagName('th')[5].children[0]).datepicker( "option", "dateFormat", 'dd/M/y' );
            } else
                tr.getElementsByTagName('th')[5].children[1].value = '';
        } else{
            tr.getElementsByTagName('th')[4].children[1].value = '';
            tr.getElementsByTagName('th')[5].children[1].value = '';
        }
        paint();
    }



function paint(){

    var miTabla = document.getElementById("table_content");

    for (var i=2; i< (miTabla.rows.length - 1); i++) {

        var tr = miTabla.getElementsByTagName('tr')[i];
        var duration = tr.getElementsByTagName('th')[3].firstChild.value;

        //var PD = miTabla.getElementsByTagName('tr')[1].getElementsByTagName('th')[6].firstChild.value;
        var PD = miTabla.getElementsByTagName('tr')[1].getElementsByTagName('th')[6].children[1].value;


        var strPlanned = miTabla.getElementsByTagName('tr')[i].getElementsByTagName('th')[4].children[1].value;
        var strActual = miTabla.getElementsByTagName('tr')[i].getElementsByTagName('th')[6].children[1].value;

        if( strPlanned != '' ){
            var splitActual;
            var strActual;
            var dateActual;

            var splitPlanned = strPlanned.split("/");
            var strPlanned = splitPlanned[1]+ "/" + splitPlanned[0] + "/20" + splitPlanned[2];
            var datePlanned = new Date(strPlanned);

            if( strActual != ''){
                var splitActual = strActual.split("/");
                var strActual = splitActual[1]+ "/" + splitActual[0] + "/20" + splitActual[2];
                dateActual = new Date(strActual);

                var result = dates.compare(datePlanned,dateActual);
                if( result == 0)
                    tr.getElementsByTagName('th')[6].children[0].style.backgroundColor='#FBFFA1'
                else if ( result > 0)
                    tr.getElementsByTagName('th')[6].children[0].style.backgroundColor='#C4F1C5'
                else
                    tr.getElementsByTagName('th')[6].children[0].style.backgroundColor='#FFBAAD'


            }else {
                dateActual = new Date();

                var result = dates.compare(datePlanned,dateActual);

                var date7 = new Date(datePlanned.getTime() - (7 * 24 * 3600 * 1000));

                var result2 = dates.compare(date7,dateActual);

                if ( result2 <= 0 && result >= 0 )
                    tr.getElementsByTagName('th')[6].children[0].style.backgroundColor='#FBFFA1'
                else {
                     if( result > 0 )
                         tr.getElementsByTagName('th')[6].children[0].style.backgroundColor='#C4F1C5'
                    else
                         tr.getElementsByTagName('th')[6].children[0].style.backgroundColor='#FFBAAD'
                }


            }




        }

        }
}

function addDays(myDate,days) {
    return new Date(myDate.getTime() + days*24*60*60*1000);
}

}


function deshabilitarFechas(){

    var miTabla = document.getElementById("table_content");
    for (var i=1; i<(miTabla.rows.length - 1); i++) {
        miTabla.getElementsByTagName('tr')[i].getElementsByTagName('th')[5].children[0].disabled = false;
        miTabla.getElementsByTagName('tr')[i].getElementsByTagName('th')[4].children[0].disabled = false;
    }

    setEmptyDates();
}


function openWindows(id, data){

       var html = '<table class="tableEdit" style="margin: 10px 0% 0% 2%;">' +
           '<tr><td><input id="id" type="hidden" value="'+ id +'"></td></tr>' +
           '<tr><td><textarea id="data" rows="10"  cols="57"  >'+data+'</textarea></td></tr>' +
           '<tr><td style="text-align: center"><input type="submit" value="Close" onclick="closeWindows()" /></td></tr>' +
           '</table>';

    $.window({
        showModal: true,
        title: 'Comments',
        modalOpacity: 0,
        content: html,
        width: 500,
        height: 300,
        resizable: false
    });

}

function closeWindows(){
    var id = "#comments_" + $('#id').val();
    $(id).val( $(data).val() );
    $.window.closeAll();

}



var dates = {
    convert:function(d) {
        // Converts the date in d to a date-object. The input can be:
        //   a date object: returned without modification
        //  an array      : Interpreted as [year,month,day]. NOTE: month is 0-11.
        //   a number     : Interpreted as number of milliseconds
        //                  since 1 Jan 1970 (a timestamp)
        //   a string     : Any format supported by the javascript engine, like
        //                  "YYYY/MM/DD", "MM/DD/YYYY", "Jan 31 2009" etc.
        //  an object     : Interpreted as an object with year, month and date
        //                  attributes.  **NOTE** month is 0-11.
        return (
            d.constructor === Date ? d :
                d.constructor === Array ? new Date(d[0],d[1],d[2]) :
                    d.constructor === Number ? new Date(d) :
                        d.constructor === String ? new Date(d) :
                            typeof d === "object" ? new Date(d.year,d.month,d.date) :
                                NaN
            );
    },
    compare:function(a,b) {
        // Compare two dates (could be of any type supported by the convert
        // function above) and returns:
        //  -1 : if a < b
        //   0 : if a = b
        //   1 : if a > b
        // NaN : if a or b is an illegal date
        // NOTE: The code inside isFinite does an assignment (=).
        return (
            isFinite(a=this.convert(a).valueOf()) &&
                isFinite(b=this.convert(b).valueOf()) ?
                (a>b)-(a<b) :
                NaN
            );
    },
    inRange:function(d,start,end) {
        // Checks if date in d is between dates in start and end.
        // Returns a boolean or NaN:
        //    true  : if d is between start and end (inclusive)
        //    false : if d is before start or after end
        //    NaN   : if one or more of the dates is illegal.
        // NOTE: The code inside isFinite does an assignment (=).
        return (
            isFinite(d=this.convert(d).valueOf()) &&
                isFinite(start=this.convert(start).valueOf()) &&
                isFinite(end=this.convert(end).valueOf()) ?
                start <= d && d <= end :
                NaN
            );
    }
}

/*
 Se recibe una fecha en formato dd/mm/yyyy, y la cantidad de días,
 en positivo para sumar, o un número negativo para restar.
 */
function calcularDifDias(fecha,dif){
    var f=new Array(),i;
    var milisegundos=parseInt(24*60*60*1000)*dif;
    fecha=fecha.split("/").reverse();
    fecha=new Date(fecha.join("/"));
    var tiempo=fecha.getTime();
    fecha.setTime(parseInt(tiempo+milisegundos));
    f[2]=fecha.getDate();
    f[1]=fecha.getMonth()+1;
    f[0]=fecha.getYear();
    if(f[1]<10)
        f[1]="0"+f[1];
    if(f[2]<10)
        f[2]="0"+f[2];
    return f.reverse().join("/") ;
};

function pepe(date){

    var d = date.getDate();
    var m = date.getMonth()+1;
    var y = date.getFullYear();
    return  (d<=9?'0'+d:d) + '/' +(m<=9?'0'+m:m) + '/' + y ;
}